// pages/order/order.js
const app = getApp();

Page({
    data: {
        orderList: [],
        isAdmin: false,
        debugInfo: '' // 添加调试信息
    },
    
    onLoad: function() {
        console.log('=== 订单页面加载 ===');
        this.checkAdminPermission();
        this.updateNavigationBarTitle();
        
        // 只有主理人才能加载订单数据
        if (this.data.isAdmin) {
            this.loadOrders();
        }
    },
    
    onShow: function() {
        console.log('=== 订单页面显示 ===');
        // 每次显示都重新检查权限
        this.checkAdminPermission();
        
        // 只有主理人且页面显示时才重新加载订单
        if (this.data.isAdmin) {
            this.loadOrders();
        }
    },
    
    // 检查管理员权限 - 修复版
    checkAdminPermission: function() {
        console.log('开始检查管理员权限');
        
        let isAdmin = false;
        let permissionSource = '';
        
        // 方法1：从全局数据获取
        if (app.globalData.isAdmin) {
            isAdmin = true;
            permissionSource = '全局数据';
            console.log('从全局数据确认是主理人');
        }
        // 方法2：从本地存储获取
        else {
            const storedIsAdmin = wx.getStorageSync('isAdmin');
            const storedUserType = wx.getStorageSync('userType');
            
            console.log('本地存储数据:', {
                storedIsAdmin: storedIsAdmin,
                storedUserType: storedUserType
            });
            
            if (storedIsAdmin || storedUserType === '主理人' || storedUserType === '私厨') {
                isAdmin = true;
                permissionSource = '本地存储';
                console.log('从本地存储确认是主理人');
                
                // 同时更新全局数据
                app.globalData.isAdmin = true;
            }
        }
        
        this.setData({ 
            isAdmin: isAdmin,
            debugInfo: `权限来源: ${permissionSource}, 状态: ${isAdmin ? '主理人' : '普通用户'}`
        });
        
        console.log('最终权限状态:', {
            isAdmin: isAdmin,
            source: permissionSource
        });
    },
    
    // 更新导航栏标题
    updateNavigationBarTitle: function() {
        wx.setNavigationBarTitle({
            title: this.data.isAdmin ? '收藏列表' : '无权限访问'
        });
    },
    
    // 加载订单数据
    loadOrders: function() {
        console.log('开始加载订单数据');
        
        try {
            // 尝试从不同键名加载订单数据
            let orderList = wx.getStorageSync('orders') || [];
            
            // 如果orders为空，尝试其他可能的键名
            if (orderList.length === 0) {
                orderList = wx.getStorageSync('orderList') || [];
            }
            if (orderList.length === 0) {
                orderList = wx.getStorageSync('userOrders') || [];
            }
            
            console.log('加载的订单数据:', orderList);
            
            // 按时间排序，最新的订单在前
            orderList.sort((a, b) => {
                const timeA = a.createTime || a.orderTime || 0;
                const timeB = b.createTime || b.orderTime || 0;
                return timeB - timeA;
            });
            
            this.setData({ 
                orderList,
                debugInfo: this.data.debugInfo + ` | 订单数: ${orderList.length}`
            });
            
        } catch (error) {
            console.error('加载订单失败:', error);
            this.setData({ orderList: [] });
            
            wx.showToast({
                title: '加载订单失败',
                icon: 'none'
            });
        }
    },
    
    // 删除订单
    deleteOrder: function(e) {
        if (!this.data.isAdmin) {
            wx.showToast({
                title: '无操作权限',
                icon: 'none'
            });
            return;
        }
        
        const orderId = e.currentTarget.dataset.id;
        console.log('删除订单:', orderId);
        
        wx.showModal({
            title: '确认删除',
            content: '确定要删除这个收藏吗？',
            success: (res) => {
                if (res.confirm) {
                    const orderList = this.data.orderList.filter(order => order.id !== orderId);
                    this.setData({ orderList });
                    
                    try {
                        // 同时更新所有可能的存储键
                        wx.setStorageSync('orders', orderList);
                        wx.setStorageSync('orderList', orderList);
                        wx.setStorageSync('userOrders', orderList);
                        
                        wx.showToast({
                            title: '删除成功',
                            icon: 'success'
                        });
                    } catch (error) {
                        console.error('删除订单失败:', error);
                        wx.showToast({
                            title: '删除失败',
                            icon: 'none'
                        });
                    }
                }
            }
        });
    },
    
    // 生成采购清单并跳转
    generatePurchaseList: function(e) {
        if (!this.data.isAdmin) {
            wx.showToast({
                title: '无操作权限',
                icon: 'none'
            });
            return;
        }
        
        const orderId = e.currentTarget.dataset.id;
        console.log("生成采购清单，订单ID:", orderId);
        
        // 跳转到采购清单页面，并传递订单ID
        wx.navigateTo({
            url: `/pages/purchase-list/purchase-list?orderId=${orderId}`
        });
    },
    
    // 返回首页
    goToHome: function() {
        wx.switchTab({
            url: '/pages/index/index'
        });
    },
    
    // 强制权限同步
    forcePermissionSync: function() {
        console.log('执行强制权限同步');
        
        // 重新检查所有可能的权限来源
        const userInfo = wx.getStorageSync('userInfo');
        const userType = wx.getStorageSync('userType');
        const isAdmin = wx.getStorageSync('isAdmin');
        const isLoggedIn = wx.getStorageSync('isLoggedIn');
        
        console.log('当前存储状态:', {
            userInfo: userInfo,
            userType: userType,
            isAdmin: isAdmin,
            isLoggedIn: isLoggedIn
        });
        
        // 如果是主理人用户，强制设置权限
        if (userInfo && isLoggedIn) {
            if (userInfo.nickName === '私厨主理人' || userType === '主理人' || userType === '私厨' || isAdmin) {
                wx.setStorageSync('isAdmin', true);
                wx.setStorageSync('userType', '主理人');
                app.globalData.isAdmin = true;
                app.globalData.userType = '主理人';
                
                this.setData({ 
                    isAdmin: true,
                    debugInfo: '强制设置为主理人权限'
                });
                
                console.log('强制设置为主理人权限成功');
                
                // 重新加载订单
                this.loadOrders();
                
                wx.showToast({
                    title: '权限同步成功',
                    icon: 'success'
                });
                return;
            }
        }
        
        wx.showToast({
            title: '无法识别主理人身份',
            icon: 'none'
        });
    },
    
    // 调试方法
    debugCheckData: function() {
        console.log('=== 调试信息 ===');
        
        const globalData = {
            isAdmin: app.globalData.isAdmin,
            userType: app.globalData.userType,
            userInfo: app.globalData.userInfo
        };
        
        const storageData = {
            isAdmin: wx.getStorageSync('isAdmin'),
            userType: wx.getStorageSync('userType'),
            userInfo: wx.getStorageSync('userInfo'),
            isLoggedIn: wx.getStorageSync('isLoggedIn'),
            orders: wx.getStorageSync('orders'),
            orderList: wx.getStorageSync('orderList'),
            userOrders: wx.getStorageSync('userOrders')
        };
        
        console.log('全局数据:', globalData);
        console.log('本地存储:', storageData);
        console.log('页面数据:', this.data);
        
        wx.showModal({
            title: '调试信息',
            content: `全局isAdmin: ${globalData.isAdmin}\n存储isAdmin: ${storageData.isAdmin}\n页面isAdmin: ${this.data.isAdmin}\n用户类型: ${storageData.userType}`,
            showCancel: false
        });
    },
    
    debugClearData: function() {
        if (!this.data.isAdmin) return;
        
        wx.showModal({
            title: '确认清除',
            content: '确定要清空所有订单数据吗？',
            success: (res) => {
                if (res.confirm) {
                    try {
                        wx.setStorageSync('orders', []);
                        wx.setStorageSync('orderList', []);
                        wx.setStorageSync('userOrders', []);
                        this.setData({ orderList: [] });
                        wx.showToast({
                            title: '数据已清除',
                            icon: 'success'
                        });
                    } catch (error) {
                        console.error('清除订单数据失败:', error);
                        wx.showToast({
                            title: '清除失败',
                            icon: 'none'
                        });
                    }
                }
            }
        });
    },

    onReady: function() {},
    onHide: function() {},
    onUnload: function() {},
    onPullDownRefresh: function() {
        if (this.data.isAdmin) {
            this.loadOrders();
        }
        wx.stopPullDownRefresh();
    },
    onReachBottom: function() {},
    onShareAppMessage: function() {
        return {
            title: '收藏列表',
            path: '/pages/order/order'
        };
    }
});